// pages/hisConsult/hisConsult.js
//获取应用实例
var webim = require('../../utils/webim_wx.js');
var webimhandler = require('../../utils/webim_handler.js');
var util = require('../../utils/util.js');

var fileData = require('../../utils/userSig.js')
var msgHandle = require('../../utils/msgHandle.js');
var serverImg="../../img/MLC.png"
const app = getApp();

// socket连接
var socketOpen = false;
var frameBuffer_Data, session, SocketTask;
var socketColes=false;



var upload_url = util.api+'/iim/contact/uploadImage';

var heart = '';

var sendHeart=true;
// 心跳失败次数
var heartBeatFailCount = 0
// 终止心跳
var heartBeatTimeOut = null;


Page({

  /**
   * Page initial data
   */
  data: {
    isNoData: false,
    noData: '../../img/no_msg.png', //无数据的图片
    contactList: [], //会话列表
    currentMsgsArray: [],
    token:'',
    url:'',
    bindUrl:'https://www.cdlpkj.cn/school/a/iim/im/index?token=C8F5BD4759534BF38630B5757C7194E3',
    navH:''
    
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function(options) {
    this.setData({
      navH: app.globalData.navHeight
    })

    // console.log(wx.getStorageSync('loginName')+'--------------------------------------')

    var that = this;


    that.setData({
      url:util.wss+wx.getStorageSync('loginName')
    })

    

  },

  onTabItemTap(item) {
    // wx.showToast({
    //   title: 'tab点击',
    // })

    var that = this;

    let token1=wx.getStorageSync('token')

    wx.request({
      url: util.api+"/iim/im/Landing",
      data: {
        token:token1,
        },
        success: function(res) {
          var tmpsig = res.data;
          console.log("the return of getUserSigByTelephone is:" + tmpsig);
          console.log(res)

        if(!tmpsig.success){

         wx.switchTab({
            url: '../index/index',
            success: function (e) {
              let page = getCurrentPages().pop();
              if (page == undefined || page == null) return;
              page.onLoad();
           }
          })
          }else{

          
          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)

          wx.switchTab({
            url: '../index/index',
            success: function (e) {
              let page = getCurrentPages().pop();
              if (page == undefined || page == null) return;
              page.onLoad();
           }
          })

          return false;
        },
      })
  },


  onUnload: function () {//如果页面被卸载时被执行
  console.log('如果页面被卸载时被执行')
  
},

  onShow: function () {

    let that=this

    
    socketColes=false


    if (!socketOpen) {
      this.webSocket()
    }


    if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
      // var chatlog=im.chatlog;  
      var im=wx.getStorageSync('im');
      console.log(im.group)       
      let currentMsgs=[];
      for(let key in im.group){
        currentMsgs.push(im.group[key])
      }
      that.setData({
        currentMsgsArray:currentMsgs
      })
    }

    if (getCurrentPages().length != 0) {
      //刷新当前页面的数据
      console.log('刷新')
      getCurrentPages()[getCurrentPages().length - 1].onLoad()
    }

    // location.reload()
    // let that=this

  },

  replace() {},

  /**
   * Lifecycle function--Called when page is initially rendered
   */


  onsocketload:function(e){
    var that = this;
    SocketTask.onOpen(res => {
      socketOpen = true;
      console.log('监听 WebSocket 连接打开事件。', res);
      that.sendTelephone();
    })
    SocketTask.onClose(onClose => {
      console.log('监听 WebSocket 连接关闭事件。', onClose)
      socketOpen = false;
      console.log(socketColes);

      if(!socketColes){
        this.webSocket();
      }
    })
    SocketTask.onError(onError => {
      console.log('监听 WebSocket 错误。错误信息', onError)
      socketOpen = false
    })



    SocketTask.onMessage(onMessage => {
      
      console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息', onMessage.data)

      if (wx.getStorageSync('userType') != "1") {
      wx.request({
        url: util.api+"/iim/im/viewUser",
        data: {id:wx.getStorageSync('userId')},
        success: function(res) {
          var tmpsig = res.data;
          if(tmpsig.success){
            console.log(tmpsig.body.data.hasOwnProperty('companyName'))

            if(!tmpsig.body.data.hasOwnProperty('companyName') && app.globalData.perfectInformat ){
              console.log('执行1243')
              app.perfectInformation()

              app.globalData.perfectInformat=false

              // that.app.globalData({
              //   perfectInformat:false
              // })

            }

          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        }
      })
      }

      var msg = onMessage.data;

      if (msg.indexOf("_msg_") >= 0) {
        var arra = msg.split("_msg_");
        var sender = arra[0];//群組id
        var receiver = arra[1];//发送者登录名
        var content = arra[2];//内容
        var avatar = arra[3];
        var type = arra[4];
        var senderName = arra[5];//发送者姓名
        var sendtime = arra[6];


        var msgtype = arra[7];
        var groupName = arra[8];//
        //var avatar1 = arra[9];
        var usertype = arra[10];

       

          // layim.getMessage({
          //   username: senderName
          //   , avatar: avatar
          //   , id: sender
          //   , type: type
          //   , content: content
          // });

          console.log(sender)
          console.log(senderName)

          if(content.indexOf('img[')>=0){

            var arra1 = content.replace("img[","").replace("]","");

            console.log(arra1)

            var list1=({ is_ai: true, img: util.imgurl+arra1, avatar:avatar ,name:senderName,sender:sender});


          }else{
            var list1=({ is_ai: true, text: content, avatar:  avatar ,name:senderName,sender:sender});

          }

          console.log('储存')
          
          if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
            var chatlog={};
            var is=false;
            var list=new Array();
            var im=wx.getStorageSync('im');
            var group=im.group;

             if(im.chatlog!=null&&im.chatlog!=''){
              chatlog=im.chatlog;
              var isexist=false;
                for(let key in im.chatlog){
                  console.log(key+"---------"+sender);
                   if(key==sender){

                    console.log("进入2");
                    list=im.chatlog[key];
                    list.push(list1);
                    chatlog[sender]=list;
                    is=true;

                    let a= group[sender].message+1;

                    console.log(a)

                    group[sender]=({ message: a ,layGroup:group[sender].layGroup,clickURL:group[sender].clickURL});

                    // group[sender]=tmpsig.body.layGroup.unreadMessage+1;
                    // wx.setStorageSync("im",{chatlog,group});
                   //  isexist=true;
                    break;
                    
                   }
                }
               if (!is){
                 console.log('新增的：' + JSON.stringify(list1));

                 //var group = {};

                 // var msgtype = arra[7];
                 // var groupName = arra[8];//
                 // var avatar1 = arra[9];

                 var laygroup = {
                   type: msgtype,
                   groupname1: groupName,
                   avatar: avatar
                 };


                 list.push(list1);
                 chatlog[sender] = list;

                 group[sender] = ({ message: 1, layGroup: laygroup, clickURL: '../mlcchat/mlcchat' });




               }
              //  else{
              //    list.push(list1);
              //    chatlog[sender] = list;
              //  }


               // if(is==false){
                
               // }
             }else{
              list.push(list1);
              chatlog[sender]=list;
             }
             wx.setStorageSync("im",{ group,chatlog});
          }else{
            //全为空的
            var chatlog = {};
            var is = false;
            var list = new Array();
          
            var group={};

            // var msgtype = arra[7];
            // var groupName = arra[8];//
            // var avatar1 = arra[9];

              var laygroup={
                type: msgtype,
                groupname1: groupName,
                avatar: avatar
              };

         
              list.push(list1);
              chatlog[sender] = list;
            
            group[sender] = ({ message: 1, layGroup: laygroup, clickURL: '../mlcchat/mlcchat' });
            wx.setStorageSync("im", { group, chatlog });

          }

              console.log('执行')

              if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
                // var chatlog=im.chatlog;  
                var im=wx.getStorageSync('im');
                console.log(im.group)       
                let currentMsgs=[];
                for(let key in im.group){
                  currentMsgs.push(im.group[key])
                }
                that.setData({
                  currentMsgsArray:currentMsgs
                })
              }
        }
        // that.bottom()
    });
  },



  onReady: function() {

    wx.removeTabBarBadge({
      index: 1
    })


    var that = this;
  
    setInterval(function () {
      console.log("----heartbeat----");
      if (socketOpen && sendHeart){
        that.startHeartBeat();
      }
    }, 10*1000);
  },

  webSocket: function () {

    var me=this;

    console.log(me.data.url)

    // 创建Socket
    console.log(me.SocketTask);
    SocketTask = wx.connectSocket({
      url: me.data.url,
      //data: 'data',
      header: {
        'content-type': 'application/json'
      },
      method: 'post',
      success: function (res) {
        console.log('WebSocket连接创建', res);
        socketOpen = true;

        setTimeout(() => {
          me.onsocketload();
        }, 100);


        setTimeout(() => {
          me.unreadInformation()
        }, 100);

     


      },
      fail: function (err) {
        wx.showToast({
          title: '网络异常！',
        })
        console.log(err)
      },
    })
  },

  onHide: function () {
    console.log('离开')
    clearInterval()

    socketColes=true;
    SocketTask.close();
    socketOpen=false;

 

  },


    // 开始心跳
    startHeartBeat: function () {
      // console.log('socket开始心跳')
      var self = this;
      heart = 'heart';
    //  self.heartBeat();
    },
  
    // 结束心跳
    stopHeartBeat: function () {
      console.log('socket结束心跳')
      var self = this;
      heart = '';
      if (heartBeatTimeOut) {
        clearTimeout(heartBeatTimeOut);
        heartBeatTimeOut = null;
      }
      if (connectSocketTimeOut) {
        clearTimeout(connectSocketTimeOut);
        connectSocketTimeOut = null;
      }
    },
  
    // 心跳
    heartBeat: function () {
      var self = this;
      if (!heart) {
        return;
      }
        sendSocketMessage({
          msg: JSON.stringify({
            'msg_type': 'heart'
          }),
          success: function (res) {
            console.log('socket心跳成功');
            if (heart) {
              heartBeatTimeOut = setTimeout(() => {
                self.heartBeat();
              }, 7000);
            }
          },
          fail: function (res) {
            console.log('socket心跳失败');
            if (heartBeatFailCount > 2) {
              // 重连
              self.connectSocket();
            }
            if (heart) {
              heartBeatTimeOut = setTimeout(() => {
                self.heartBeat();
              }, 7000);
            }
            heartBeatFailCount++;
          },
        });
        }
  
    //end heartBeat
  
    ,sendTelephone:function(){
      var that=this;
      sendSocketMessage({
        msg: JSON.stringify({
          'telephone': app.globalData.identifier
        }),
        success: function (res) {
          console.log('send telephone successfully!');
        },
        fail: function (res) {
          console.log('send telephone failed');
            // 重连
            that.connectSocket();
        }
      });
    },//end sendTelephone
  



unreadInformation(){
  let that=this

  wx.request({
    url: util.api+"/iim/im/unreadInformation",
    data: {
      loginName:wx.getStorageSync('loginName'),
      },
      success: function(res) {
        var tmpsig = res.data;

        console.log("the return of getUserSigByTelephone is:" + tmpsig);
        console.log(tmpsig)

        if(!tmpsig.success){

        }else{
          
        for(let i=0;i<tmpsig.body.data.length;i++){

          var msg = tmpsig.body.data[i];
          if (msg.indexOf("_msg_") >= 0) {
            var arra = msg.split("_msg_");
            var sender = arra[0];//群組id
            var receiver = arra[1];//发送者登录名
            var content = arra[2];//内容
            var avatar = arra[3];
            var type = arra[4];
            var senderName = arra[5];//发送者姓名
            var sendtime = arra[6];
            var msgtype = arra[7];
            var groupName = arra[8];//
            //var avatar1 = arra[9];
            var usertype = arra[10];

            console.log(sender)
            console.log(senderName)
           

            if(content.indexOf('img[')>=0){

              var arra1 = content.replace("img[","").replace("]","");
  
              console.log(arra1)
  
              var list1=({ is_ai: true, img: util.imgurl+arra1, avatar:  avatar ,name:senderName,sender:sender});
  
  
            }else{
              var list1=({ is_ai: true, text: content, avatar:  avatar ,name:senderName,sender:sender});
            }
  
            console.log('储存')
            
            if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
              var chatlog={};
              var is=false;
              var list=new Array();
              var im=wx.getStorageSync('im');
              var group=im.group;
  
               if(im.chatlog!=null&&im.chatlog!=''){
                chatlog=im.chatlog;
                  for(let key in im.chatlog){
                    console.log(key+"---------"+sender);
                     if(key==sender){
  
                      console.log("进入2");
                      list=im.chatlog[key];
                      list.push(list1);
                      chatlog[sender]=list;
                      is=true;
  
                      let a= group[sender].message+1;
  
                      console.log(a)
  
                      group[sender]=({ message: a ,layGroup:group[sender].layGroup,clickURL:group[sender].clickURL});
  
                      // group[sender]=tmpsig.body.layGroup.unreadMessage+1;
                      // wx.setStorageSync("im",{chatlog,group});
  
                      break;
                     }
                  }
                  if(!is){
                    console.log('新增的：' + JSON.stringify(list1));

                    //var group = {};

                    // var msgtype = arra[7];
                    // var groupName = arra[8];//
                    // var avatar1 = arra[9];

                    var laygroup = {
                      type: msgtype,
                      groupname1: groupName,
                      avatar: avatar
                    };


                    list.push(list1);
                    chatlog[sender] = list;

                    group[sender] = ({ message: 1, layGroup: laygroup, clickURL: '../mlcchat/mlcchat' });
                    
                  }
                  // else{
                  //   list.push(list1);
                  //   chatlog[sender] = list;
                  // }
               }
               
               else{
                list.push(list1);
                chatlog[sender]=list;
               }
               
               wx.setStorageSync("im",{ group,chatlog});
            }else{
              //全为空的
              var chatlog = {};
              var is = false;
              var list = new Array();

              var group = {};

              // var msgtype = arra[7];
              // var groupName = arra[8];//
              // var avatar1 = arra[9];

              var laygroup = {
                type: msgtype,
                groupname1: groupName,
                avatar: avatar
              };


              list.push(list1);
              chatlog[sender] = list;

              group[sender] = ({ message: 1, layGroup: laygroup, clickURL: '../mlcchat/mlcchat' });
              wx.setStorageSync("im", { group, chatlog });
            }

                console.log('执行')

                if(wx.getStorageSync('im')!=null&&wx.getStorageSync('im')!=''){
                  // var chatlog=im.chatlog;  
                  var im=wx.getStorageSync('im');
                  console.log(im.group)       
                  let currentMsgs=[];
                  for(let key in im.group){
                    currentMsgs.push(im.group[key])
                  }
                  that.setData({
                    currentMsgsArray:currentMsgs
                  })
                }
            }
          }
        }
      },
      fail: function(resp) {
        console.log("getUserSigByTelephone failed,the response is %o", resp)
        return false;
      },
    })

},
  

})
// end Page


//通过 WebSocket 连接发送数据，需要先 wx.connectSocket，并在 wx.onSocketOpen 回调之后才能发送。
function sendSocketMessage(msg) {
  var that = this;
  console.log(SocketTask)
  console.log(msg)

  console.log('通过 WebSocket 连接发送数据', (msg))
  SocketTask.send({
    data: msg
  }, function (res) {
    console.log('已发送', res)
  })
};